﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.Configuration;

namespace HYBYSoft.Company.WebSite.Helper
{
    /// <summary>
    /// 当前用户信息
    /// </summary>
    public class CurrentUserInfo
    {
        /// <summary>
        /// 用户编号
        /// </summary>
        public int UserId
        { get; set; }

        /// <summary>
        /// 用户名
        /// </summary>
        public string Name
        { get; set; }

        /// <summary>
        /// 企业编号
        /// </summary>
        public int CompanyId
        { get; set; }

        /// <summary>
        /// 登录时间
        /// </summary>
        public DateTime LoginTime
        { get; set; }
    }

    public class SecurityHelper
    {
        /// <summary>
        /// 对字符串进行MD5加密并进行Base64编码
        /// </summary>
        /// <param name="text">要加密的字符串</param>
        /// <returns></returns>
        public static string CreateHashAndBase64(string text)
        {
            byte[] plaintText = Encoding.UTF8.GetBytes(text);

            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] hashedtext = md5.ComputeHash(plaintText);
            string hashandbase64 = Convert.ToBase64String(hashedtext);

            md5.Clear();
            Array.Clear(plaintText, 0, plaintText.Length);

            return hashandbase64;
        }

        /// <summary>
        /// 获得当前的用户信息
        /// </summary>
        /// <returns></returns>
        public static CurrentUserInfo GetCurrentUserInfo()
        {
            string cookieString = GetCookie(ConstDefinition.TOKEN_NAME);

            //判断用户是否登录
            if (!string.IsNullOrEmpty(cookieString))
            {
                byte[] cookiesByteArray = Convert.FromBase64String(cookieString);
                string[] cookiesInfo = (Encoding.UTF8.GetString(cookiesByteArray)).Split('$');

                return new CurrentUserInfo
                {
                    UserId = int.Parse(cookiesInfo[0]),
                    Name = cookiesInfo[1],
                    CompanyId = int.Parse(cookiesInfo[2]),
                    LoginTime = DateTime.Parse(cookiesInfo[3])
                };
            }

            return new CurrentUserInfo();
        }

        /// <summary>
        /// 读取Cookie
        /// </summary>
        /// <param name="cookieName">Cookie名称</param>
        /// <returns></returns>
        private static string GetCookie(string cookieName)
        {
            if (HttpContext.Current.Request.Cookies[cookieName] != null)
            {
                return HttpContext.Current.Request.Cookies[cookieName].Value;
            }
            return string.Empty;
        }
    }
}